package com.pig4cloud.pig.village.api.vo;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Base64;

/**
 * @author limbray.li
 * @date 2021/7/27
 */
public class BASE64DecodedMultipartFile implements MultipartFile {

	private final byte[] imgContent;
	private final String name;
	private final String originalFilename;
	private final String contentType;

	public BASE64DecodedMultipartFile(byte[] imgContent, Base64File base64File) {
		this.imgContent = imgContent;
		this.name = base64File.getName();
		this.originalFilename = base64File.getOriginalFilename();
		this.contentType = base64File.getContentType();
	}

	@Override
	public String getName() {
		return this.name;
	}

	@Override
	public String getOriginalFilename() {
		return this.originalFilename;
	}

	@Override
	public String getContentType() {
		return this.contentType;
	}

	@Override
	public boolean isEmpty() {
		return imgContent == null || imgContent.length == 0;
	}

	@Override
	public long getSize() {
		return imgContent.length;
	}

	@Override
	public byte[] getBytes() throws IOException {
		return imgContent;
	}

	@Override
	public InputStream getInputStream() throws IOException {
		return new ByteArrayInputStream(imgContent);
	}

	@Override
	public void transferTo(File dest) throws IOException, IllegalStateException {
		new FileOutputStream(dest).write(imgContent);
	}

	public static MultipartFile base64ToMultipart(Base64File base64File) {
		byte[] b;
		b = Base64.getDecoder().decode(base64File.getBase64Data());

		for (int i = 0; i < b.length; ++i) {
			if (b[i] < 0) {
				b[i] += 256;
			}
		}
		return new BASE64DecodedMultipartFile(b, base64File);
	}

}
